package com.ztjava.portal.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseService;
import com.ztjava.portal.model.PortalRole;
import com.ztjava.portal.model.PortalUser;
import com.ztjava.portal.model.PortalUserRole;

public class PortalService extends BaseService{
	public List<Record> getUserRightsMenu(String menuConfig,Integer user_id){
		List<PortalRole> list = PortalRole.dao.find("select * from "+PortalRole.tablename+" where id in (select role_id from "+PortalUserRole.tablename+" where user_id=?)",user_id);
		String rights = "";
		for(PortalRole portalRole:list){
			if(portalRole.get("rights")!=null&&!portalRole.getStr("rights").equals("")){
				rights = rights + portalRole.getStr("rights")+",";
			}
		}
		if(!rights.equals("")){
			rights = rights.substring(0,rights.length()-1);
		}
		CacheKit.put(Constant.CacheCommon, "PORTAL_RIGHTS_"+user_id,rights);
		
		List<Record> menuList = CacheKit.get(Constant.CacheData,menuConfig);
		if(user_id==1){
			return menuList;
		}else {
			List<Record> userMenuList = checkRights(menuList,rights);
			return userMenuList;
		}
	}
	public PortalUser getUserByUsername(String username) {
		return PortalUser.dao.findFirst("select * from "+PortalUser.tablename+" where username = ?",username);
	}
	

	public List<Record> checkRights(List<Record> list,String rights){
		List<Record> rightsList = new ArrayList<Record>();
		Record vo = null;
		for(int i=0;i<list.size();i++){
			vo = list.get(i);
			if(vo.get("rights")!=null){
				if((","+rights+",").indexOf(","+vo.getStr("rights")+",")<0){
					continue;
				}
			}
			Record record = new Record();
			record.set("name", vo.getStr("name"));
			if(vo.get("url")!=null){
				record.set("url", vo.getStr("url"));
			}
			if(vo.get("icon")!=null){
				record.set("icon", vo.getStr("icon"));
			}else {
				if(vo.get("children")!=null){
					record.set("icon", "fa fa-clone");
				}else {
					record.set("icon", "fa fa-genderless");
				}
			}
			if(vo.get("children")!=null){
				record.set("children", checkRights((List<Record>)vo.get("children"),rights));
			}
			rightsList.add(record);
		}
		if(rightsList.size()==0){
			return null;
		}
		return rightsList;
	}
	
	//Role模块
	public List<PortalRole> getRoleList(){
		return PortalRole.dao.find("select * from "+PortalRole.tablename+" order by id asc");
	}
}
